//
//  UISegmentedControl+Helper.m
//  ZAYY
//
//  Created by Vic on 2019/12/3.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "UISegmentedControl+Helper.h"

@implementation UISegmentedControl (Helper)

- (void)segmentedIOS13Style {
    if (@available(iOS 13, *)) {
        UIColor *tintColor = [self tintColor];
        UIImage *tintColorImage = [self imageWithColor:tintColor];
        
        // Must set the background image for normal to something (even clear) else the rest won't work
        [self setBackgroundImage:[self imageWithColor:self.backgroundColor ? self.backgroundColor : [UIColor clearColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        [self setBackgroundImage:tintColorImage forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
        [self setBackgroundImage:[self imageWithColor:[tintColor colorWithAlphaComponent:0.2]] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
        [self setBackgroundImage:tintColorImage forState:UIControlStateSelected|UIControlStateSelected barMetrics:UIBarMetricsDefault];
//        [self setTitleTextAttributes:@{NSForegroundColorAttributeName: tintColor, NSFontAttributeName: [UIFont systemFontOfSize:Font_SIZE_11]} forState:UIControlStateNormal];
        [self setTitleTextAttributes:@{NSForegroundColorAttributeName:THEMECOLOR_OF_TEXT_333333, NSFontAttributeName:FontBold(Font_18)} forState:UIControlStateSelected];
        [self setTitleTextAttributes:@{NSForegroundColorAttributeName:THEMECOLOR_OF_TEXT_9a9a9a, NSFontAttributeName:Font(Font_18)} forState:UIControlStateNormal];
        
        [self setDividerImage:tintColorImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//        self.layer.borderWidth = self.layer.borderWidth ? self.layer.borderWidth : 1;
//        self.layer.borderColor = self.layer.borderColor ? self.layer.borderColor : [COLOR_OF_CLEAR CGColor];
        self.selectedSegmentTintColor = tintColor;
    } else {
        
    }
}

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

@end
